<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2018/9/3
 * Time: 15:51
 */

namespace App\Repositories;

use App\Http\Helper\BeanHelper;
use App\Models\TestingPartRecord;
use DB;

class TestingPartRecordRepository extends Repository
{
    /**
     * 获取最新的用户测评的记录
     * @param $uid
     * @param $tid
     * @return mixed
     */
    public function getLastOneByUid($uid, $tid) {
        return BeanHelper::convertStdClsToArr(
            TestingPartRecord::where([
                'uid' => $uid,
                'tid' => $tid,
            ])->orderBy('id', 'desc')->first()
        );
    }

    /**
     * 获取用户 times 次的所有维度测评信息
     * @param $uid
     * @param $tid
     * @param $times
     * @return mixed
     */
    public function getByUidAndTimes($uid, $tid, $times) {
        return BeanHelper::convertStdClsToArr(
            TestingPartRecord::where([
                'uid' => $uid,
                'tid' => $tid,
                'evaluation_times' => $times,
            ])->orderBy('dimension', 'asc')->get()
        );
    }

    /**
     * 获取 times 次第 dimension 维度的记录
     * @param $uid
     * @param $tid
     * @param $dimension
     * @param $times
     * @return mixed
     */
    public function getOneByUidAndDimension($uid, $tid, $dimension, $times) {
        return BeanHelper::convertStdClsToArr(
            TestingPartRecord::where([
                'uid' => $uid,
                'tid' => $tid,
                'dimension' => $dimension,
                'evaluation_times' => $times,
            ])->first()
        );
    }

    /**
     * 获取某一维度用户的答题次数
     * @param $uid
     * @param $tid
     * @param $dimension
     * @param $times
     * @return mixed
     */
    public function getTimesByUidTidDimension($uid, $tid, $dimension) {
        return TestingPartRecord::where([
            'uid' => $uid,
            'tid' => $tid,
            'dimension' => $dimension,
        ])->max('evaluation_times');
    }

    /**
     * 根据用户ID获取最新的维度记录
     * @param $uid
     * @return array
     */
    public function getLastDimensionListByUid($uid) {
        $sql = <<<SQL
SELECT * FROM testing_part_record WHERE uid=$uid 
AND evaluation_times=(SELECT MAX(evaluation_times) FROM testing_part_record WHERE dimension=6 AND uid=$uid)
SQL;
        $list = DB::select($sql);
        return BeanHelper::convertStdClsToArr($list);
    }

    /**
     * 插入数据
     * @param $data
     * @return mixed
     */
    public function store($data) {
        return TestingPartRecord::firstOrCreate($data);
    }

    public function model()
    {
        return app(TestingPartRecord::class);
    }

    public function tag()
    {
        // TODO: Implement tag() method.
    }
}